<template>
<div class="login">
  <div class="login-box">
    <!-- 头部区域 -->
    <div class="avatar">
      <img src="../assets/heima.png" alt="">
    </div>
    <!-- 表单结构 -->
    <!-- 通过rules来定义规则，看文档 -->
    <!-- 利用 ref 可拿到表单组件 -->
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" class="login_form">
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" prefix-icon="iconfont icon-3702mima"></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" @click="login">登录</el-button>
        <el-button type="info" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<script>
export default {
  data () {
    return {
      // 表单数据
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 表单验证规则
      loginFormRules: {
        // 用户名登录规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {

  },

  methods: {
    // 重置表单
    resetForm () {
      // 重置表单
      this.$refs.loginForm.resetFields()
    },
    login () {
      // console.log(this)
      this.$refs.loginFormRef.validate(async flag => {
        // console.log(flag)
        if (!flag) return
        const { data: res } = await this.$axios.post('/login', this.loginForm)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('登录失败')
        this.$message.success('登录成功')
        // 设置token值
        sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.login {
    width: 100%;
    height: 100%;
    background-color: #2b4b6b;
    .login-box {
      width: 450px;
      height: 300px;
      background: #fff;
      border-radius: 7px;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);

      .avatar {
      width: 100px;
      height: 100px;
      border: 1px solid #eee;
      border-radius: 50%;
      padding: 10px;
      box-shadow: 0px 0px 10px orangered;
      position: absolute;
      left: 50%;
      transform: translate(-50%);
      top:-50px;
      background: #fff;
      margin-bottom: 100px;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
      }
    }
    .login_form {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 0 15px;
    box-sizing: border-box;
    .btns {
      float: right;
    }
    }
  }
}
</style>
